// 菜单接口
const db = require('../../db')

/**
 * 新增菜单
 * @param {*} req 
 * @param {*} res 
 * @returns 
 */
exports.createMenu = (req, res) => {
    const { name, path, parent_id = 0, icon, sort = 0, status = 1 } = req.body
    // 验证必填字段
    if (!name || !path) {
        return res.status(400).json({ code: 400, message: '菜单名称和路径为必填项' })
    }
    // 验证状态值
    if (![0, 1].includes(Number(status))) {
        return res.status(400).json({ code: 400, message: '状态值无效，必须为0或1' })
    }
    // 检查菜单名称是否已存在
    const checkSql = 'select * from menus where name = ?'
    db.query(checkSql, [name], (err, results) => {
        if (err) return res.status(500).json({ code: 500, message: '服务器错误：' + err.message })
        if (results.length > 0) return res.status(400).json({ code: 400, message: '菜单名称已存在' })
        
        // 插入新菜单
        const insertSql = 'insert into menus (name, path, parent_id, icon, sort, status, created_at, updated_at) values (?, ?, ?, ?, ?, ?, NOW(), NOW())'
        db.query(insertSql, [name, path, parent_id, icon || null, sort, status], (err, result) => {
            if (err) return res.status(500).json({ code: 500, message: '服务器错误：' + err.message })
            res.status(200).json({
                code: 200,
                message: '菜单创建成功',
            })
        })
    })
}

/**
 * 删除菜单
 * @param {*} req 
 * @param {*} res 
 * @returns 
 */
exports.deleteMenu = (req, res) => {
    const { id } = req.body
    // 验证必填字段
    if (!id) {
        return res.status(400).json({ code: 400, message: '菜单ID为必填项' })
    }
    
    // 检查菜单是否存在
    const checkSql = 'select * from menus where id = ?'
    db.query(checkSql, [id], (err, results) => {
        if (err) return res.status(500).json({ code: 500, message: '服务器错误：' + err.message })
        if (results.length === 0) return res.status(404).json({ code: 404, message: '菜单不存在' })
        
        // 检查是否有子菜单
        const checkChildSql = 'select * from menus where parent_id = ?'
        db.query(checkChildSql, [id], (err, childResults) => {
            if (err) return res.status(500).json({ code: 500, message: '服务器错误：' + err.message })
            if (childResults.length > 0) return res.status(400).json({ code: 400, message: '该菜单下有子菜单，无法删除' })
            
            // 删除菜单
            const deleteSql = 'delete from menus where id = ?'
            db.query(deleteSql, [id], (err, result) => {
                if (err) return res.status(500).json({ code: 500, message: '服务器错误：' + err.message })
                res.status(200).json({
                    code: 200,
                    message: '菜单删除成功',
                })
            })
        })
    })
}

/**
 * 更新菜单
 * @param {*} req 
 * @param {*} res 
 * @returns 
 */
exports.updateMenu = (req, res) => {
    const { id, name, path, parent_id, icon, sort, status } = req.body
    // 验证必填字段
    if (!id) {
        return res.status(400).json({ code: 400, message: '菜单ID为必填项' })
    }
    if (!name || !path) {
        return res.status(400).json({ code: 400, message: '菜单名称和路径为必填项' })
    }
    // 验证状态值
    if (status !== undefined && ![0, 1].includes(Number(status))) {
        return res.status(400).json({ code: 400, message: '状态值无效，必须为0或1' })
    }
    
    // 检查菜单是否存在
    const checkSql = 'select * from menus where id = ?'
    db.query(checkSql, [id], (err, results) => {
        if (err) return res.status(500).json({ code: 500, message: '服务器错误：' + err.message })
        if (results.length === 0) return res.status(404).json({ code: 404, message: '菜单不存在' })
        
        // 检查菜单名称是否与其他菜单重复
        const checkNameSql = 'select * from menus where name = ? and id != ?'
        db.query(checkNameSql, [name, id], (err, nameResults) => {
            if (err) return res.status(500).json({ code: 500, message: '服务器错误：' + err.message })
            if (nameResults.length > 0) return res.status(400).json({ code: 400, message: '菜单名称已存在' })
            
            // 更新菜单
            const updateSql = 'update menus set name = ?, path = ?, parent_id = ?, icon = ?, sort = ?, status = ?, updated_at = NOW() where id = ?'
            db.query(updateSql, [name, path, parent_id || 0, icon || null, sort || 0, status || 1, id], (err, result) => {
                if (err) return res.status(500).json({ code: 500, message: '服务器错误：' + err.message })
                res.status(200).json({
                    code: 200,
                    message: '菜单更新成功',
                })
            })
        })
    })
}

/**
 * 获取菜单列表
 * @param {*} req 
 * @param {*} res 
 * @returns 
 */
exports.getMenuList = (req, res) => {
    const name = req.query.name
    const status = req.query.status
    
    // 构建WHERE子句
    let whereClause = ''
    let params = []
    // 根据菜单名称查询
    if (name && name.trim() !== '') {
        whereClause += 'name LIKE ? '
        params.push(`%${name}%`)
    }
    // 根据状态查询
    if (status !== undefined && status !== '') {
        whereClause += whereClause ? 'AND status = ? ' : 'status = ? '
        params.push(status)
    }
    whereClause = whereClause ? 'WHERE ' + whereClause : ''
    
    // 查询所有菜单
    const sql = `select * from menus ${whereClause} order by sort asc, id asc`
    db.query(sql, params, (err, results) => {
        if (err) return res.status(500).json({ code: 500, message: '服务器错误：' + err.message })
        
        // 构建树形结构
        const menuTree = buildMenuTree(results)
        
        res.status(200).json({
            code: 200,
            message: '获取菜单列表成功',
            data: menuTree
        })
    })
}

/**
 * 构建菜单树形结构
 * @param {Array} menus 菜单列表
 * @returns {Array} 树形结构菜单
 */
function buildMenuTree(menus) {
    // 先找出所有的一级菜单
    const rootMenus = menus.filter(menu => menu.parent_id === 0)
    
    // 递归构建子菜单
    const buildChildren = (parentMenu) => {
        const children = menus.filter(menu => menu.parent_id === parentMenu.id)
        if (children.length > 0) {
            parentMenu.children = children
            children.forEach(child => buildChildren(child))
        }
        return parentMenu
    }
    
    // 为每个一级菜单构建子菜单
    return rootMenus.map(rootMenu => buildChildren(rootMenu))
}
